<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" :confirm-button-text="false"
            :cancel-button-text="false" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="应用名称" prop="app_name">
                    <el-input v-model="formData.app_name" clearable placeholder="请输入应用名称" :disabled="true" />
                </el-form-item>
                <el-form-item label="工具栏地址" prop="tools_url">
                    <div class="input-with-tools">
                        <el-input v-model="formData.tools_url" clearable :disabled="true" />
                        <div class="tool-buttons">
                            <el-tooltip content="复制" placement="top">
                                <el-button type="text" @click="handleCopyUrl" size="small">
                                    复制
                                </el-button>
                            </el-tooltip>
                            <el-tooltip content="预览" placement="top">
                                <el-button type="text" @click="handlePreviewUrl" size="small">
                                    预览
                                </el-button>
                            </el-tooltip>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="应用描述" prop="description">
                    <el-input class="flex-1" v-model="formData.description" type="textarea" :rows="4" clearable
                        show-word-limit :disabled="true" />
                </el-form-item>
                <el-form-item label="工具栏充值描述" prop="pay_desc">
                    <el-input class="flex-1" v-model="formData.pay_desc" type="textarea" :rows="4" clearable
                        show-word-limit :disabled="true" />
                </el-form-item>
                <el-form-item label="接口选择" prop="interface_list">
                    <div class="interface-selection">
                        <div v-for="category in interfaceData" :key="category.cid" class="category-item">
                            <div class="category-header" style="cursor: pointer">
                                <span @click="toggleCategory(category.cid)">
                                    {{ categoryCollapsed[category.cid] ? '▶' : '▼' }}
                                    {{ category.name }}
                                </span>
                                <el-checkbox :indeterminate="isIndeterminate(category.cid)"
                                    v-model="categoryChecked[category.cid]"
                                    @change="handleCategoryChange(category.cid, $event)">
                                    全选
                                </el-checkbox>
                            </div>
                            <div class="interface-checkboxes" v-if="!categoryCollapsed[category.cid]">
                                <el-checkbox-group v-model="selectedInterfaces" class="ml-4" :disabled="true">
                                    <el-checkbox v-for="inter in category.children" :key="inter.id" :label="inter.id"
                                        class="mr-4 mt-2" :disabled="true">
                                        {{ inter.name }}
                                    </el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="interfaceAppListEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {
    apiInterfaceAppListAdd,
    apiInterfaceAppListEdit,
    apiInterfaceAppListDetail
} from '@/api/interface_app_list'
import { apiInterfaceListByCate } from '@/api/interface'
import type { PropType } from 'vue'
import { ElMessage } from 'element-plus'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '应用详情' : '新增接口应用列表'
})

const route = useRoute(); // 获取路由实例
// 表单数据
const formData = reactive({
    id: '',
    app_name: '',
    description: '',
    pay_desc: '',
    interface_list: '',
    tools_url: ''
})

// 复制URL到剪贴板
const handleCopyUrl = () => {
    if (!formData.tools_url) {
        ElMessage.warning('工具栏地址为空，无法复制');
        return;
    }
    navigator.clipboard.writeText(formData.tools_url).then(() => {
        ElMessage.success('复制成功');
    }).catch(() => {
        ElMessage.error('复制失败，请手动复制');
    });
}

// 预览URL
const handlePreviewUrl = () => {
    if (!formData.tools_url) {
        ElMessage.warning('工具栏地址为空，无法预览');
        return;
    }
    window.open(formData.tools_url, '_blank');
}


// 接口分类数据
const interfaceData = ref<any[]>([])
// 表单验证
// 是否全选状态
const categoryChecked = ref<Record<string | number, boolean>>({})
const categoryCollapsed = ref<Record<string | number, boolean>>({})
const selectedInterfaces = ref<number[]>([])

const isIndeterminate = (cid: string | number) => {
    const category = interfaceData.value.find((cat) => cat.cid === cid)
    if (!category || !category.children || category.children.length === 0) return false

    const total = category.children.length
    const selected = category.children.filter((inter) =>
        selectedInterfaces.value.includes(inter.id)
    ).length

    return selected > 0 && selected < total
}

const toggleCategory = (cid: string | number) => {
    categoryCollapsed.value[cid] = !categoryCollapsed.value[cid]
}

const handleCategoryChange = (cid: string | number, checked: boolean) => {
    const category = interfaceData.value.find((cat) => cat.cid === cid)
    if (!category || !category.children) return

    const interfaceIds = category.children.map((inter) => inter.id)
    if (checked) {
        // 添加该分类下所有未选中的接口
        interfaceIds.forEach((id) => {
            if (!selectedInterfaces.value.includes(id)) {
                selectedInterfaces.value.push(id)
            }
        })
    } else {
        // 移除该分类下所有接口
        selectedInterfaces.value = selectedInterfaces.value.filter(
            (id) => !interfaceIds.includes(id)
        )
    }
}
// 表单验证
const formRules = reactive<any>({})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
        if (key == 'id') continue;
        // 获取域名并增加容错
        const domain = import.meta.env.VITE_APP_BASE_URL || window.location.origin || '';
        if (!domain) {
            ElMessage.warning('域名配置缺失，请联系管理员');
        }
        formData.tools_url = `${domain}/tools/#/home/${formData.id}`;
    }

    // Parse interface_list into selectedInterfaces array
    if (data.interface_list) {
        selectedInterfaces.value = data.interface_list.split(',').map((id) => Number(id.trim()))
    } else {
        selectedInterfaces.value = []
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiInterfaceAppListDetail({
        id: row.id
    })
    setFormData(data)
}
const getInterfaceListBycate = async () => {
    const data = await apiInterfaceListByCate({})
    interfaceData.value = data
    // 初始化所有分类为展开状态
    data.forEach((category) => {
        categoryCollapsed.value[category.cid] = false
    })
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    getInterfaceListBycate()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
<style scoped>
.category-item {
    margin-bottom: 20px;
    padding-left: 10px;
}

.category-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.category-header span {
    margin-right: 10px;
    min-width: 80px;
}

.interface-checkboxes {
    margin-left: 90px;
    /* 与分类标题对齐 */
    width: calc(100% - 90px);
    padding-left: 20px;
    border-left: 1px solid #e5e7eb;
}

.input-with-tools {
    display: flex;
    align-items: center;
    gap: 4px;
    /* 减小间距 */
    width: 100%;
}

.input-with-tools .el-input {
    flex: 1;
    /* 让输入框占据剩余空间 */
    min-width: 0;
    /* 允许输入框收缩 */
}

.tool-buttons {
    display: flex;
    gap: 2px;
    /* 减小按钮间距 */
    white-space: nowrap;
    /* 防止按钮换行 */
}

/* 移除按钮默认内边距 */
.tool-buttons .el-button--text {
    padding: 0 6px;
}
</style>